package org.msz.framework.security.filter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 此处进行角色转换，因为keycloak中存在 Realm 的领域角色与 Client 的客户端角色，此处将所有的角色都
 */
public class CustomJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> {

    private String clientId;

    @Override
    public Collection<GrantedAuthority> convert(Jwt jwt) {
        Set<GrantedAuthority> authorities = new HashSet<>();

        // Extract realm roles
        Map<String, Object> realmAccess = jwt.getClaim("realm_access");
        if (realmAccess != null) {
            Collection<String> roles = (Collection<String>) realmAccess.get("roles");
            if (roles != null) {
                roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
            }
        }

        // Extract client roles
        Map<String, Object> resourceAccess = jwt.getClaim("resource_access");
        if (resourceAccess != null) {
            resourceAccess.forEach((key, value) -> {
                //此处只保留领域角色和客户端角色，如果需要所有角色，注释此if
                if(key.equals(clientId)){
                    if (value instanceof Map) {
                        Map<String, Object> clientRoles = (Map<String, Object>) value;
                        Collection<String> roles = (Collection<String>) clientRoles.get("roles");
                        if (roles != null) {
                            roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
                        }
                    }
                }

            });
        }

        return authorities;
    }

    public CustomJwtGrantedAuthoritiesConverter(String clientId) {
        this.clientId = clientId;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }
}
